<?php

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Model\Category;
use Admin\Form\CategoryForm;

class CategoryController extends AbstractActionController {

	/* @var Admin\Model\CategoryTable $categoryTable */
	protected $categoryTable;

	public function indexAction() {
//		pr($this->getCategoryTable()->fetchAll());die;
		return new ViewModel(array(
			'categories' => $this->getCategoryTable()->fetchAll(),
		));
	}

	public function addAction() {
		$form = new CategoryForm();
		$form->get('submit')->setValue('Add');

		$request = $this->getRequest();


		if ($request->isPost()) {
			$category = new Category();
			$form->setInputFilter($category->getInputFilter());
			$form->setData($request->getPost());
			
			if ($form->isValid()) {
				$category->exchangeArray($form->getData());
				$this->getCategoryTable()->save($category);
				return $this->redirect()->toRoute('category');
			}
		}
		return array('form' => $form);
	}

	public function editAction() {
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) {
			return $this->redirect()->toRoute('category', array(
						'action' => 'add'
			));
		}

		try {
			$category = $this->getCategoryTable()->get($id);
		} catch (\Exception $ex) {
			return $this->redirect()->toRoute('category', array(
						'action' => 'index'
			));
		}

		$form = new CategoryForm();
		$form->bind($category);
		$form->get('submit')->setAttribute('value', 'Edit');

		$request = $this->getRequest();
		if ($request->isPost()) {
			$form->setInputFilter($category->getInputFilter());
			$form->setData($request->getPost());

			if ($form->isValid()) {
				$this->getCategoryTable()->save($form->getData());

				return $this->redirect()->toRoute('category');
			}
		}

		return array(
			'id' => $id,
			'form' => $form,
		);
	}

	public function deleteAction() {
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) {
			return $this->redirect()->toRoute('category');
		}

		$request = $this->getRequest();
		if ($request->isPost()) {
			$del = $request->getPost('del', 'No');

			if ($del == 'Yes') {
				$id = (int) $request->getPost('id');
				$this->getCategoryTable()->delete($id);
			}

			return $this->redirect()->toRoute('category');
		}

		return array(
			'id' => $id,
			'category' => $this->getCategoryTable()->get($id)
		);
	}

	/**
	 * 
	 * @return CategoryTable
	 */
	public function getCategoryTable() {
		if (!$this->categoryTable) {
			$sm = $this->getServiceLocator();
			$this->categoryTable = $sm->get('Admin\Model\CategoryTable');
		}
		return $this->categoryTable;
	}

}